package com.jt.service;

import com.jt.dao.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 定义UserDetailsService接口的具体实现类,在这个实现定义用户登陆逻辑
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;


    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String pass = passwordEncoder.encode("123456");
        System.out.println(pass);
        //1.基于用户名查询用户信息
        Map<String, Object> map = userMapper.userNameSelect(username);
        if (map==null)throw new UsernameNotFoundException("username is not correct");
        //2.基于用户id查询权限信息
        List<String> list = userMapper.SelectUserPermissions((Long) map.get("id"));

        List<GrantedAuthority> grantedAuthorities =
              AuthorityUtils.commaSeparatedStringToAuthorityList(
                        "sys:res:retrieve,sys:res:create");
        ///
        User user=new User(username,(String) map.get("password"),AuthorityUtils.createAuthorityList(list.toArray(new String[]{})));
        return user;
    }
}
